-- cost_attrib
-- create by wangy
-- 道具：扣除属性

return {
    apply = function(source, target, classId, value)
        local props;
        local args;

        local function doCost(source, value)
            local count = value[2];
            local key   = value[1];

            -- 魔法值最多扣除至0点
            if key == "mp" then
                local mp = source:queryAttrib("mp");
                count = math.min(count, mp);

                -- 免疫魔法扣除效果
                props = PropM.fetchProps(source, "property_immunity");
                for _, prop in ipairs(props) do
                    args  = {["value"] = count, ["class_id"] = classId,};
                    count = PropM.trigger(source, prop[1], prop[2], args);
                end
            end

            -- 生命值最多扣除至1点
            if key == "hp" then
                local hp = source:queryAttrib("hp");
                count = math.min(count, hp - 1);

                -- 免疫生命扣除效果
                props = PropM.fetchProps(source, "property_immunity");
                for _, prop in ipairs(props) do
                    args  = {["value"] = count, ["class_id"] = classId,};
                    count = PropM.trigger(source, prop[1], prop[2], args);
                end
            end

            -- 扣除
            if type(key) == "number" then
                ItemM.costAmount(ME.user, key, count);
            elseif type(key) == "string" and count > 0 then
                ME.user:costAttrib(key, count);
            end
        end

        if type(value[1]) ~= 'table' then
            -- 扣除单个属性
            doCost(source, value);
        else
            -- 扣除多个属性
            for _, cost in pairs(value) do
                doCost(source, cost);
            end
        end
    end,
};
